package com.bawei.shoppingcar.gridviewgift_demo;

import androidx.appcompat.app.AppCompatActivity;

import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.GridView;

import com.bawei.shoppingcar.R;
import com.google.gson.Gson;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class GiftActivity extends AppCompatActivity {
    private GridView gv;
    private GiftAdapter adapter;
    private List<GiftEntity.DataBean> mList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gift);
        gv = findViewById(R.id.gv);
        adapter = new GiftAdapter(mList,this);
        gv.setAdapter(adapter);
        new GiftTask().execute("http://43.143.146.165:7777/gift/json");
    }
    class GiftTask extends AsyncTask<String,Void,String>{

        @Override
        protected String doInBackground(String... strings) {

            try {
                URL url=new URL(strings[0]);
                HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.connect();
                if(httpURLConnection.getResponseCode()==200)
                {
                    InputStream inputStream=httpURLConnection.getInputStream();
                    byte[] buffer=new byte[1024];
                    int len=0;
                    StringBuilder stringBuilder=new StringBuilder();
                    while ((len=inputStream.read(buffer))!=-1)
                    {
                        stringBuilder.append(new String(buffer,0,len));
                    }
                    return  stringBuilder.toString();
                }
            } catch (MalformedURLException e) {   e.printStackTrace();
            } catch (IOException e) {  e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            GiftEntity giftEntity = new Gson().fromJson(s, GiftEntity.class);
            List<GiftEntity.DataBean> data = giftEntity.getData();
            mList.addAll(data);
            adapter.notifyDataSetChanged();
        }
    }

}